
if exists (select * from sys.objects where object_id = OBJECT_ID(N'[dbo].[cms_udf_SplitIntegers]') and type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
drop function [dbo].[cms_udf_SplitIntegers]
go

create function [dbo].[cms_udf_SplitIntegers]
(
    @ids varchar(8000)
)
returns @integers table
(
    integer int primary key
)
as
begin
declare @splitLength int, @delimiter varchar(5)
    
set @delimiter = ','
    
while len(@ids) > 0
begin 
	select @splitLength =
		case charindex(@delimiter, @ids)
			when 0 then len(@ids)
				else charindex(@delimiter, @ids) - 1
		end
 
    insert into @integers 
    select cast(substring(@ids, 1 ,@splitLength) as int)
		where not exists (select * from @integers where integer = cast(substring(@ids, 1 ,@splitLength) as int))
    
    select @ids = 
		case (len(@ids) - @splitLength)
			when 0 then  ''
				else right(@ids, len(@ids) - @splitLength - 1)
		end 	
end
return  
end
